package practise;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo02_DataSource {
    public static void main(String[] args) {
        // 创建连接池
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        // 设置参数
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/java113?characterEncoding=utf8&allowPublicKeyRetrieval" +
                "=true&useSSL=false");
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("123456");

        // 定义JDBC 源对象
        DataSource dataSource = mysqlDataSource;

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = null;

        try {
            // 获取连接
            connection = dataSource.getConnection();
            // 获得预处理对象
            Scanner in = new Scanner(System.in);
            System.out.println("请输入名字");
            String name = in.nextLine();
            // 为什么可以保证安全呢？ 因为将对其经行预编译 -> ' -> \' 之类的方法使其成为一个整体
            String sql = "select student_id, sn, name, mail, class_id from student where name = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, name);
            // 执行
            resultSet = preparedStatement.executeQuery();
            // 打印
            while (resultSet.next()) {
                long stuId = resultSet.getLong(1);
                String sn = resultSet.getString(2);
                String uname = resultSet.getString(3);
                String mail = resultSet.getString(4);
                long classId = resultSet.getLong(5);
                System.out.println(MessageFormat.format("学生id={0}, 学生学号={1}, 学生姓名={2}, 学生邮箱={3}, 班级id={4}", stuId, sn, uname, mail, classId));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 依次释放资源，关闭连接
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
